﻿using System.Collections.ObjectModel;
using System.Windows;
using Microsoft.Phone.Controls;
using RssReaderTemplate.Model;
using RssReaderTemplate.ViewModels;
using System;
using System.Windows.Navigation;
using System.Windows.Controls;
using System.Linq;
using Microsoft.Phone.Shell;
using RssReaderTemplate.Globalization;

namespace RssReaderTemplate.Views
{
    public partial class Categories : PhoneApplicationPage
    {
        CategoriesViewModel _viewModel;

        public Categories()
        {
            InitializeComponent();
            BuildApplicationBar();
        }

        public void BuildApplicationBar()
        {
            ApplicationBarIconButton button = new ApplicationBarIconButton(new Uri("/icons/appbar.folder.rest.png", UriKind.Relative))
            {
                Text = AppResources.Categories,
            };
            button.Click += List_Click;
            ApplicationBar.Buttons.Add(button);
            button = new ApplicationBarIconButton(new Uri("/icons/About.png", UriKind.Relative))
            {
                Text = AppResources.About
            };
            button.Click += About_Click;
            ApplicationBar.Buttons.Add(button);
        }

        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            this.State["ViewModel"] = _viewModel;
            _viewModel.Dispose();
            base.OnNavigatingFrom(e);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            object viewModel;
            if (!State.TryGetValue("ViewModel", out viewModel))
            {
                _viewModel = ViewModelCollection.CategoriesViewModel;
            }
            else
            {
                _viewModel = viewModel as CategoriesViewModel;
            }
            foreach (var cat in _viewModel.Categories)
            {
                cat.SelectedItemIndex = -1;
            }
            DataContext = _viewModel;
            base.OnNavigatedTo(e);
        }

        void Categories_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var cat = _viewModel.Categories[_viewModel.CurrentCategory];
            if (cat.SelectedItemIndex == -1)
            {
                return;
            }
            var elem = cat.Elements[cat.SelectedItemIndex];
            int index = _viewModel.Items.IndexOf(elem);
            NavigationService.Navigate(new Uri(string.Format("/Views/Details.xaml?id={0}&index={1}",elem.Id.ToString(), index), UriKind.Relative));
        }

        private void List_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/MainPage.xaml", UriKind.Relative));
        }

        private void About_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Views/About.xaml", UriKind.Relative));
        }
    }
}